<?php
//decode by http://奥森世纪/
namespace app\home\controller;

use think\Controller;
use think\Db;
use app\home\model\Withdraw;
use app\admin\model\Config;
use app\home\model\Member;
use app\home\model\CreditRecord;
use app\admin\model\InvitationRebateRecord;

class Wdraw extends Base {



    public function withdraw_do(){
        $member = $this->checkLogin();
        $config = Config::getInfo();
        $sett = $config['setting'];

        if($member['level']>1){
            $setting = ['withdraw_min' => 1, 'withdraw_fee' => $sett['withdraw_fee_member']];
        }
        if($member['level']<=1){
            $setting = ['withdraw_min' => 1, 'withdraw_fee' => $sett['withdraw_fee']];
        }




        if(request()->isAjax()){
            $params = request()->post();
            $result = $this->validate($params,'Withdraw');
            if($result !== true){
                message($result,'','error');
            }

            if($params['credit2']>1000){
                message('单次最高提现1000元','','error');
            }
            if($params['credit2'] < $setting['withdraw_min']){
                message('提现金额不能少于'.$setting['withdraw_min'].'元','','error');
            }
            if($params['pay_method']==2 && $member['openid']==''){
                message('微信第一次提现请用微信识别下面二维码绑定微信','','error');
            }

            //处理是整数的
            params_floor(['credit2'], $params);
            $params['fee'] = $params['credit2'] * ($setting['withdraw_fee'] / 100);
            $credit2 = ($params['credit2'] + $params['fee']);
            if($credit2 > $member['credit2']){
                $canmoney = floor($member['credit2']/(1+$setting['withdraw_fee'] / 100));
                $feemoney=floor($member['credit2'] * ($setting['withdraw_fee'] / 100));
                message('最多可提现'.$canmoney.'元'.'包含手续费'.$feemoney.'元','','error');
            }

            // message('系统维护中...','','error');

            if($member['tx_day']==date('Ymd')){
                message('每天仅可提现一次','','error');
            }

            Db::startTrans();

            $status1 = Member::updateCreditById($member['uid'], 0, -$credit2);
            if(!$status1){
                Db::rollback();
                message('提现失败：-1','','error');
            }
            /*
            $statistics = Db::name('statistics')->where('time',date('Ymd'))->inc('tixian',$params['credit2'])->inc('tx_sx',$params['fee'])->update();
            if(!$statistics){
                Db::rollback();
                message('提现失败：-8','','error');
            }
            */
            //记录提现操作
            $status2 = CreditRecord::addInfo([
                'uid' => $member['uid'],
                'type' => 'credit2',
                'num' => -$credit2,
                'title' => '提现',
                'remark' => "申请提现到账号：" . $params['account'] . "，扣除{$credit2}余额。",
                'create_time' => TIMESTAMP
            ]);
            if(!$status2){
                Db::rollback();
                message('提现失败：-2','','error');
            }

            //记录提现单子
            $withdraw_data = [
                'uid' => $member['uid'],
                'username' => $member['username'],
                'credit2' => $params['credit2'],
                'fee' => $params['fee'],
                'pay_method' => $params['pay_method'],
                'realname' => $member['alipay_realname'],
                'create_time' => TIMESTAMP
            ];

            if($params['pay_method']==2){
                $channel='wx';
                $withdraw_data['account'] = $params['account'];
                if(!$member['tx_wx']){
                	db('member')->where('uid',$member['uid'])->setField('tx_wx',$params['account']);
                }
            }else{
                $channel='ali';

            //设置账户
                 //支付宝
                if($member['alipay_account'] !=''){
                    $withdraw_data['account'] = $member['alipay_account'];
                }else{
                    $withdraw_data['account'] = $params['account'];
                    db('member')->where('uid',$member['uid'])->setField('alipay_account',$params['account']);
                }
            }
/*

                //判断该账号今天是否有人提现
                $today=strtotime(date('Ymd'));
                $withdraw_where=[
                    'uid'=>$member['uid'],
                    'create_time'=>['gt',$today],
                ];
                $has_withdraw=db('withdraw')->where($withdraw_where)->find();

                if($has_withdraw){
                        Db::rollback();
                        message('该账号今天已提现','','error');
                }

*/
                if($params['credit2']>1){

                }else{
                	
                            if($params['pay_method']==2){
                	
	                			//微信支付
	                        	$withdraw_data['status'] = 1;
	                            //$host='#';
	                            $host='#';
	                            $api='/api/api/withdraw';
	                            $url=$host.$api;
	                            $appid='#';
	                            $secret_key='#';
	
	                            $data=[
	                              "appid"=>$appid,
	                              "channel"=>$channel,
	                              "order_no"=>$member['uid'].rand(100000,999999),
	                              "amount"=>$params['credit2'],
	                              "description"=>'用户提现',
	                              'recipient_openid'=>$member['openid']
	                            ];
                            
                            
	                           // dump($data);die;
	                            $sign=sign($data,$secret_key);
	                            $data['sign']=$sign;
	
	                            $ch = curl_init();
	                            curl_setopt($ch, CURLOPT_URL, $url);
	                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	                            curl_setopt($ch, CURLOPT_POST, 1);
	                            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	            				$pay_rst=curl_exec($ch);
	                            curl_close($ch);
	            			//	dump($pay_rst);
	                            $pay_arr = json_decode($pay_rst,true);
	                          //$pay_arr=json_decode($pay_str,true);
	                       //   dump($pay_arr);
	                          if($pay_arr['code'] != 40011 && $pay_arr['code'] != 40010){
	                                Db::rollback();
	                                message($pay_arr['errmsg'],'','error');
	                          }
                            	
                            }else{
                            	
                            	//支付宝支付

                                    // $data=[
                                    //   "appid"=>$appid,
                                    //   "channel"=>$channel,
                                    //   "order_no"=>$member['uid'].rand(100000,999999),
                                    //   "amount"=>$params['credit2'],
                                    //   "recipient_account_type"=>'ALIPAY_LOGONID',
                                    //   "recipient_account"=>$params['account'],
                                    //   "recipient_name"=>$member['alipay_realname'],
                                    //   "description"=>'用户提现',
                                    // ];
                                   $withdraw_data['status'] = 1;
                                    	
                                   $ddx_rst= $this->ddx_pay($params['account'],$member['alipay_realname'],$params['credit2']);
                                
                                   if($ddx_rst['code'] != 200){
	                                   	Db::rollback();
		                                message($ddx_rst['msg'],'','error');
                                   }
                                    
                            }
 
						//发放奖励
						withdraw_reward($member,$params['credit2']);
                }

            $status3 = Withdraw::addInfo($withdraw_data);

            if(!$status3){
                Db::rollback();
                message('提现失败：-3','','error');
            }

            //提现成功以后把提现日期做修改
            db('member')->where('uid',$member['uid'])->setField('tx_day',date('Ymd'));
            Db::commit();


            message('提现成功，请耐心等待平台审核，预计24小时内到帐','reload','success');
        }





    }



	public function ddx_pay($payee_account,$payee_real_name,$amount){
		$url='#';
		$apikey='#';
	//	$payee_account='13673631252';
		$token="#";
		//$amount=0.1;
		
		$send_data=[
			'apikey'=>$apikey,
			'payee_account'=>$payee_account,
			'amount'=>$amount,
			'payer_show_name'=>'闲猫',
			'payee_real_name'=>$payee_real_name,
			'remark'=>'闲猫提现',
			];
		$signature=$this->create_signature($send_data,$token);
		
		$send_data['signature']=$signature;
	
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $send_data);
		$pay_rst=curl_exec($ch);
        curl_close($ch);
        $pay_arr=json_decode($pay_rst,1);
        //dump($pay_rst);
		
		return $pay_arr;
	}

 public  function create_signature($data, $token)
 {
     ksort($data);
     return md5(http_build_query($data) . '&token=' . trim($token));
 }


}